from os.path import join as pjoin

from buildutils import quoted

Import('env', 'install', 'buildSample')
localenv = env.Clone()

# (program name, [source files])
samples = [('demo', ['demo.f90'])]

for programName, sources in samples:
    buildSample(localenv.Program, programName, sources,
                F90PATH='#build/src/fortran',
                LIBS=['cantera_fortran']+env['cantera_libs']+env['cxx_stdlib'],
                LIBPATH=[env['sundials_libdir'], env['blas_lapack_dir'],
                         env['extra_lib_dirs'], env["hdf_libdir"], '#build/lib'],
                LINK='$FORTRAN_LINK')

    # Generate SConstruct files to be installed
    linkflags = ["-g", localenv["thread_flags"]]
    incdirs = [pjoin(localenv["ct_incroot"], "cantera")] # path to fortran .mod
    libdirs = [localenv["ct_libdir"]]
    if not localenv["package_build"]:
        linkflags.append(f"-Wl,-rpath,{localenv['ct_shlibdir']}")
        libdirs.extend([localenv["sundials_libdir"], localenv["blas_lapack_dir"]])
        libdirs.append(localenv["hdf_libdir"])
        libdirs.extend(localenv["extra_lib_dirs"])
        libdirs = sorted(set(libdirs))

    libs = ['cantera_fortran'] + localenv['cantera_libs'] + env['cxx_stdlib']

    localenv['tmpl_cantera_incdirs'] = repr([x for x in incdirs if x])
    localenv['tmpl_cantera_libs'] = repr(libs)
    localenv['tmpl_cantera_libdirs'] = repr([x for x in libdirs if x])
    localenv['tmpl_cantera_linkflags'] = repr([x for x in linkflags if x])
    localenv['tmpl_cantera_frameworks'] = repr(localenv['FRAMEWORKS'])

    localenv['tmpl_progname'] = programName
    localenv['tmpl_sourcename'] = programName + '.f90'

    if localenv['package_build']:
        # For package builds, use environment variables or rely on SCons to find the
        # default compiler
        localenv['tmpl_f90'] = "env['F90'] = os.environ.get('F90', env['F90'])"
    else:
        # Otherwise, use the same compiler that was used to build Cantera, with the
        # environment variables optionally overriding
        localenv['tmpl_f90'] = env.subst("env['F90'] = os.environ.get('F90', '$F90')")

    sconstruct = localenv.SubstFile('SConstruct', 'SConstruct.in')
    install("$inst_sampledir/f90", sconstruct)

    # Generate CMakeLists.txt to be installed
    localenv['cmake_cantera_incdirs'] = ' '.join(quoted(x) for x in incdirs if x)
    localenv['cmake_cantera_libs'] = ' '.join(libs)
    localenv['cmake_cantera_libdirs'] = ' '.join(quoted(x) for x in libdirs if x)
    cmakelists = localenv.SubstFile('CMakeLists.txt', 'CMakeLists.txt.in')
    install("$inst_sampledir/f90", cmakelists)
